<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h1>{{ isRegister ? '注册' : '原始记录设计系统' }}</h1>
        <p>{{ isRegister ? '创建新账户' : '欢迎回来，请登录您的账户' }}</p>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="0"
        size="large"
        @submit.prevent="handleSubmit"
      >
        <!-- 注册时额外的字段 -->
        <template v-if="isRegister">
          <el-form-item prop="username">
            <el-input
              v-model="form.username"
              placeholder="用户名"
              :prefix-icon="User"
              maxlength="50"
            />
          </el-form-item>
        </template>

        <el-form-item prop="email">
          <el-input
            v-model="form.email"
            placeholder="邮箱地址"
            :prefix-icon="Message"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
            maxlength="50"
          />
        </el-form-item>

        <el-form-item v-if="isRegister" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="确认密码"
            :prefix-icon="Lock"
            show-password
            maxlength="50"
          />
        </el-form-item>

        <el-form-item v-if="!isRegister">
          <div class="login-options">
            <el-checkbox v-model="form.rememberMe">记住我</el-checkbox>
            <el-link type="primary" @click="showForgotPassword = true">
              忘记密码？
            </el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleSubmit"
            style="width: 100%"
          >
            {{ isRegister ? '注册' : '登录' }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="switch-mode">
            <span>还没有账户？请联系管理员</span>
            <el-link type="primary" href="mailto:huxuexue9284@sinovac.com">huxuexue9284@sinovac.com</el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="showForgotPassword"
      title="忘记密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form ref="forgotFormRef" :model="forgotForm" :rules="forgotRules">
        <el-form-item prop="email">
          <el-input
            v-model="forgotForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            prefix-icon="Message"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showForgotPassword = false">取消</el-button>
          <el-button 
            type="primary" 
            :loading="forgotLoading"
            @click="handleForgotPassword"
          >
            发送重置邮件
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { User, Message, Lock } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const forgotLoading = ref(false)
const isRegister = ref(false)
const showForgotPassword = ref(false)
const formRef = ref()
const forgotFormRef = ref()

// 开发模式标识
const isDev = import.meta.env.MODE === 'development'

// 表单数据
const form = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  rememberMe: false
})

const forgotForm = reactive({
  email: ''
})

// 验证规则
const formRules = computed(() => {
  const baseRules = {
    email: [
      { required: true, message: '请输入用户名或邮箱地址', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ]
  }

  if (isRegister.value) {
    return {
      ...baseRules,
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 50, message: '用户名长度在3-50个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== form.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
  }

  return baseRules
})

const forgotRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 方法
const toggleMode = () => {
  isRegister.value = !isRegister.value
  // 清空表单
  Object.keys(form).forEach(key => {
    if (typeof form[key] === 'string') {
      form[key] = ''
    } else if (typeof form[key] === 'boolean') {
      form[key] = false
    }
  })
  formRef.value?.clearValidate()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    if (isRegister.value) {
      await handleRegister()
    } else {
      await handleLogin()
    }
  } catch (error) {
    console.error('Form validation failed:', error)
  } finally {
    loading.value = false
  }
}

const handleLogin = async () => {
  try {
    await authStore.login({
      username: form.email, // 后端支持邮箱作为用户名登录
      password: form.password
    })

    ElMessage.success('登录成功')
    
    // 跳转到原来想访问的页面，或者默认首页
    const redirect = route.query.redirect || '/'
    router.push(redirect)
  } catch (error) {
    ElMessage.error(error.message || '登录失败')
  }
}

const handleRegister = async () => {
  try {
    await authStore.register({
      username: form.username,
      email: form.email,
      password: form.password,
    })

    ElMessage.success('注册成功')
    router.push('/')
  } catch (error) {
    ElMessage.error(error.message || '注册失败')
  }
}

const handleForgotPassword = async () => {
  if (!forgotFormRef.value) return

  try {
    const valid = await forgotFormRef.value.validate()
    if (!valid) return

    forgotLoading.value = true
    
    await authStore.forgotPassword(forgotForm.email)
    
    ElMessage.success('重置密码邮件已发送，请查收邮箱')
    showForgotPassword.value = false
    forgotForm.email = ''
  } catch (error) {
    ElMessage.error(error.message || '发送邮件失败')
  } finally {
    forgotLoading.value = false
  }
}

</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;

  .login-box {
    width: 100%;
    max-width: 400px;
    background: white;
    border-radius: 16px;
    padding: 40px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);

    .login-header {
      text-align: center;
      margin-bottom: 32px;

      h1 {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
        margin: 0 0 8px 0;
      }

      p {
        color: #909399;
        margin: 0;
        font-size: 14px;
      }
    }

    .login-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }

    .switch-mode {
      text-align: center;
      width: 100%;
      font-size: 14px;
      color: #909399;

      span {
        margin-right: 8px;
      }
    }
  }
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}
</style> 